package com.hcryan.djm.handler;

import com.hcryan.djm.exception.BaiduMapException;
import com.hcryan.djm.exception.ErrorMessage;
import com.hcryan.djm.exception.TravelException;
import com.hcryan.djm.result.WebResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author ryanwdj
 * @since 2025/2/18
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(TravelException.class)
    public WebResult<String> exceptionHandler(TravelException ex){
        logError(ex);
        return WebResult.failure(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(BaiduMapException.class)
    public WebResult<String> exceptionHandler(BaiduMapException ex){
        logError(ex);
        return WebResult.failure(ErrorMessage.EXTERNAL_ERROR);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public WebResult<String> exceptionHandler(MissingServletRequestParameterException ex){
        logError(ex);
        String message = "缺少必填参数："+ex.getParameterName();
        return WebResult.failure(ErrorMessage.ERROR.getCode(),message);
    }

    @ExceptionHandler(Exception.class)
    public WebResult<String> exceptionHandler(Exception ex){
        logError(ex);
        // 返回通用的错误信息
        return WebResult.failure(ErrorMessage.INTERNAL_ERROR.getCode(), ErrorMessage.INTERNAL_ERROR.getMessage());
    }

    private void logError(Exception ex){
        // 获取触发异常的类名和方法名
        StackTraceElement[] stackTrace = ex.getStackTrace();
        String className = stackTrace.length > 0 ? stackTrace[0].getClassName() : "UnknownClass";
        String methodName = stackTrace.length > 0 ? stackTrace[0].getMethodName() : "UnknownMethod";
        // 打印详细的错误日志
        log.error("GlobalExceptionHandler#exceptionHandler - Exception in {}#{}", className, methodName, ex);
    }
}
